﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using Transport.Areas.Administrator.Models;
using Transport.Core.Models.Customers;
using Transport.Core.Models.Settings;
using Transport.Infrastructure;
using Transport.Infrastructure.Mvc;
using Transport.Services;
using Transport.Services.Customers;
using Transport.Services.Infrastructure;
using Transport.Services.Parcels;
using Transport.Services.Settings;

namespace Transport.Areas.Administrator.Controllers
{
    [Authorize]
    public class CustomerController : ControllerBase<ICustomerRepository, Customer>
    {
        private readonly IParcelRepository _parcelRepository;
        private readonly IRatesTableRepository _ratesTableRepository;

        public CustomerController(IUnitOfWork unitOfWork, ICustomerRepository repository, IParcelRepository parcelRepository,
                                  IRatesTableRepository ratesTableRepository)
            : base(repository, unitOfWork)
        {
            _parcelRepository = parcelRepository;
            _ratesTableRepository = ratesTableRepository;
        }

        //
        // GET: /Administrator/Customer/

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GridModel(string search)
        {
            var model = Repository.Search(search).Where(p => p.MyOfficeId == WorkContext.MyOfficeId);

            var gridModel = new GridModel<CustomerModel>
            {
                Data = model.Select(x => new CustomerModel
                                             {
                                                 Address = x.Address,
                                                 CustomerId = x.CustomerId,
                                                 CustomerName = x.CustomerName,
                                                 PhoneNumber = x.PhoneNumber,
                                                 Fax = x.Fax,
                                                 CustomerCode = x.CustomerCode
                                             })
            };
            return new JsonResult
            {
                Data = gridModel
            };
        }

        public ActionResult Create()
        {
            var model = new CustomerModel();
            return View(model);
        }

        public virtual ActionResult Edit(int id)
        {
            var entity = Repository.GetById(id);
            var model = new CustomerModel()
            {
                Address = entity.Address,
                CustomerId = entity.CustomerId,
                CustomerName = entity.CustomerName,
                Fax = entity.Fax,
                PhoneNumber = entity.PhoneNumber,
                CustomerCode = entity.CustomerCode,
                DiscountPercent = entity.DiscountPercent,
                UseSpecialRateTable = entity.UseSpecialRateTable,
                CustomerShortName = entity.CustomerShortName
            };
            return View("Edit", model);
        }

        [HttpPost, ValidateInput(false)]
        public virtual ActionResult Save(CustomerModel customerModel)
        {
            if (!ModelState.IsValid)
            {
                return View("Create", customerModel);
            }
            //Check existed
            var modelExisted = Repository.GetAll().FirstOrDefault(p => p.CustomerCode == customerModel.CustomerCode && p.MyOfficeId == WorkContext.MyOfficeId);
            if ((modelExisted != null && modelExisted.CustomerId != customerModel.CustomerId) || (modelExisted != null && customerModel.CustomerId <= 0))
            {
                this.SetErrorNotification("Mã khách hàng này đã tồn tại trong hệ thống.");
                return View("Create", customerModel);
            }
            if (customerModel.CustomerId <= 0) //Create News
            {
                var customer = new Customer()
                {
                    IsDeleted = false,
                    Address = customerModel.Address,
                    CustomerName = customerModel.CustomerName,
                    Fax = customerModel.Fax,
                    PhoneNumber = customerModel.PhoneNumber,
                    CustomerCode = customerModel.CustomerCode,
                    MyOfficeId = WorkContext.MyOfficeId,
                    DiscountPercent = customerModel.DiscountPercent,
                    UseSpecialRateTable = customerModel.UseSpecialRateTable,
                    CustomerShortName = customerModel.CustomerShortName
                };
                using (UnitOfWork)
                {
                    Repository.Insert(customer);
                }
                this.SetSuccessNotification(string.Format("{0} đã được lưu thành công.", "Khách hàng"));
                return RedirectToAction("Edit", new { id = customer.CustomerId, area = "Administrator" });
            }
            else //Edit user
            {
                var customer = Repository.GetById(customerModel.CustomerId);
                customer.Address = customerModel.Address;
                customer.CustomerName = customerModel.CustomerName;
                customer.Fax = customerModel.Fax;
                customer.PhoneNumber = customerModel.PhoneNumber;
                customer.CustomerCode = customerModel.CustomerCode;
                customer.MyOfficeId = WorkContext.MyOfficeId;
                customer.DiscountPercent = customerModel.DiscountPercent;
                customer.UseSpecialRateTable = customerModel.UseSpecialRateTable;
                customer.CustomerShortName = customerModel.CustomerShortName;
                if (customer.UseSpecialRateTable)
                {
                    CreateRateTables(customerModel.CustomerId);
                }
                using (UnitOfWork)
                {
                    Repository.Update(customer);
                }
                this.SetSuccessNotification(string.Format("{0} đã được lưu thành công.", "Khách hàng"));
                return RedirectToAction("Edit", new { id = customer.CustomerId, area = "Administrator" });
            }

            //Save success
            this.SetSuccessNotification(string.Format("{0} đã được lưu thành công.", "Khách hàng"));
            return RedirectToAction("Index", new { area = "Administrator" });
        }

        public ActionResult Delete(int id)
        {
            try
            {
                using (UnitOfWork)
                {
                    var entity = Repository.GetById(id);
                    entity.IsDeleted = true;
                    entity.CustomerCode = entity.CustomerCode + "_Deleted";
                    var parcels = _parcelRepository.GetAll().Where(p => p.CustomerId == id);
                    foreach (var parcel in parcels)
                    {
                        parcel.IsDeleted = true;
                        parcel.TrackingNumbers = parcel.TrackingNumbers +"_Deleted";
                    }
                }
                this.SetSuccessNotification("Khách hàng đã được xóa thành công.");
            }
            catch
            {
                this.SetErrorNotification("Khách hàng này không thể xóa, vì đã được sử dụng!");
            }
            return RedirectToAction("index", new { area = "Administrator" });
        }

        private void CreateRateTables(int customerId)
        {
            var existedRateTable = _ratesTableRepository.GetAll().Any(p => p.CustomerId == customerId);
            if (existedRateTable)
            {
                return;
            }
            var pages = new List<RatesTable>
                            {
                                new RatesTable()
                                {
                                    Description = "Đến 50",
                                    IsExtraColumn = false,
                                    MaxWeight = 50,
                                    MinWeight = 0,
                                    PriceColumnA = 8000,
                                    PriceColumnB = 12500,
                                    PriceColumnC = 12000,
                                    PriceColumnD = 12500,
                                    PriceColumnE = 10500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 50 => 100",
                                    IsExtraColumn = false,
                                    MaxWeight = 100,
                                    MinWeight = 50,
                                    PriceColumnA = 10200,
                                    PriceColumnB = 15000,
                                    PriceColumnC = 15500,
                                    PriceColumnD = 17000,
                                    PriceColumnE = 12500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 100 => 250",
                                    IsExtraColumn = false,
                                    MaxWeight = 250,
                                    MinWeight = 100,
                                    PriceColumnA = 12500,
                                    PriceColumnB = 17000,
                                    PriceColumnC = 20000,
                                    PriceColumnD = 24000,
                                    PriceColumnE = 16000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 250 => 500",
                                    IsExtraColumn = false,
                                    MaxWeight = 500,
                                    MinWeight = 250,
                                    PriceColumnA = 15000,
                                    PriceColumnB = 23000,
                                    PriceColumnC = 27500,
                                    PriceColumnD = 31500,
                                    PriceColumnE = 30000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 500 => 1000",
                                    IsExtraColumn = false,
                                    MaxWeight = 1000,
                                    MinWeight = 500,
                                    PriceColumnA = 17000,
                                    PriceColumnB = 32000,
                                    PriceColumnC = 38500,
                                    PriceColumnD = 45500,
                                    PriceColumnE = 41500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 1000 => 1500",
                                    IsExtraColumn = false,
                                    MaxWeight = 1500,
                                    MinWeight = 1000,
                                    PriceColumnA = 22000,
                                    PriceColumnB = 41500,
                                    PriceColumnC = 47000,
                                    PriceColumnD = 58000,
                                    PriceColumnE = 53000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 1500 => 2000",
                                    IsExtraColumn = false,
                                    MaxWeight = 2000,
                                    MinWeight = 1500,
                                    PriceColumnA = 26500,
                                    PriceColumnB = 49500,
                                    PriceColumnC = 56000,
                                    PriceColumnD = 69500,
                                    PriceColumnE = 63000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },
                                new RatesTable()
                                {
                                    Description = "500 gr tiếp theo",
                                    IsExtraColumn = true,
                                    MaxWeight = 0,
                                    MinWeight = 0,
                                    PriceColumnA = 2800,
                                    PriceColumnB = 5000,
                                    PriceColumnC = 6100,
                                    PriceColumnD = 9000,
                                    PriceColumnE = 8000,
                                    WeightOver = 500,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = WorkContext.MyOfficeId,
                                    CustomerId = customerId
                                },

                            };

            pages.ForEach(c => _ratesTableRepository.Insert(c));
        }
    }
}
